package com.situ.stl.controller;

import com.situ.stl.entity.Admin;
import com.situ.stl.entity.Result;
import com.situ.stl.service.AdminService;
import com.situ.stl.util.JWTUtil;
import com.situ.stl.vo.AdminVo;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * Controller层 - 管理员
 */
@CrossOrigin
@RestController
@RequestMapping( value = "/admin")
@Slf4j
public class AdminController{

    /**
     */
    @Autowired
    private AdminService adminService;

    /**
     * add
     */
    @PostMapping
    public Result add(@RequestBody Admin admin) {
        try {
            adminService.add(admin);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * remove
     */
    @DeleteMapping
    public Result remove( Integer id) {
        try {
            adminService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * edit
     */
    @PutMapping
    public Result edit( @RequestBody Admin admin) {
        try {
            adminService.edit(admin);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * getAll
     */
    @GetMapping
    public Result getAll( Integer page, Integer limit, Admin admin) {
        if ( page == null && limit == null) {
        	return Result.success(adminService.search(admin));
        } else {
        	return Result.success(adminService.searchByPage(page, limit, admin));
        }
    }

    /**
     * getById
     */
    @GetMapping( value = "/{id}")
    public Result getById( @PathVariable( value = "id") Integer id) {
        return Result.success(adminService.getById(id));
    }

    /**
     * 用户登录
     * @return  成功后返回当前用户的Token
     */
    @PostMapping( value = "/login")
    public Result login(@RequestBody AdminVo loginAdmin) {

        // 尝试登录
        try {
            // 检查验证码
            System.out.println(loginAdmin.getKey());
            if (! StringUtils.hasText(loginAdmin.getKey())) {
                throw new Exception("无效的Key！");
            }
            Claims claims = null;
            String lodCaptcha = null;

            try {
                claims = JWTUtil.parseJWT(loginAdmin.getKey());
                // 老的码
                lodCaptcha = (String) claims.getSubject();
            } catch (Exception e) {
                throw new Exception("验证码过期！");
            }

            if (!lodCaptcha.equalsIgnoreCase(loginAdmin.getCaptcha())) {
                throw new Exception("验证码错误！");
            }

        	// 调用业务
        	Admin admin = adminService.login(loginAdmin);
        	// 生成Token
            String token = JWTUtil.createJWT(admin.getPhone());
        	// 返回Token
        	return Result.success(token);
        } catch (Exception e) {
            log.error(e.getMessage());
        	return Result.error(e.getMessage());
        }
    }

    /**
     * logout， 没用了
     */
    @GetMapping( value = "/logout")
    public Result logout( HttpSession session) {
        // 退出登录
        session.invalidate();
        return Result.success();
    }

    /**
     * register
     */
    @PostMapping( value = "/reg")
    public Result reg( Admin admin, String repassword, String vercode, HttpSession session) {
        // 检查验证码
        String oldVercode = (String)session.getAttribute("vercode");
        if (oldVercode == null || !oldVercode.equals(vercode.toUpperCase())) {
        	return Result.error("验证码错误");
        }

        // 尝试登录
        try {
        	// 调用业务
        	int res = adminService.reg(admin, repassword);
        	// 返回数据
        	return Result.success(res);
        } catch (Exception e) {
        	e.printStackTrace();
        	return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @GetMapping("/getLogin")
    public Result getLogin(HttpServletRequest request) {
        // 获取Token
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            try {
                // 解析Token
                Claims claim = JWTUtil.parseJWT(token);
                String phone = claim.getSubject();
                // 查询用户
                Admin admin = adminService.getByPhone(phone);

                if (!ObjectUtils.isEmpty(admin)) {
                    return Result.success(admin);
                }
            } catch (Exception e) {
                log.info("token解析失败");
            }
        }

        return Result.error("用户未登录！！");
    }

}
